package com.dang.alex.servlet.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.dang.alex.model.Order;
import com.dang.alex.model.ReceiveAddress;
import com.dang.alex.model.User;
import com.dang.alex.service.ReceiveAddressService;
import com.dang.alex.service.imp.ServiceDAOFactory;
import com.dang.alex.servlet.shoppingCar.CartItem;

@WebServlet("/order.do")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 5281685395163193062L;
	private static final String METHOD_CONFIRM = "0";
	private static final String METHOD_SUBMIT = "1";
	private static final String METHOD_ADDRESS = "2";
	private static final String METHOD_FINISH = "3";
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method=req.getParameter("method");
		HttpSession session=req.getSession();
		Map<Integer, CartItem> map=(Map<Integer, CartItem>)session.getAttribute("s_car");
		if(method!=null) {
			switch(method) {
			case OrderServlet.METHOD_CONFIRM:
				confirm(req,resp,map);
				break;
			case OrderServlet.METHOD_SUBMIT:
				submit(req,resp);
				break;
			case OrderServlet.METHOD_ADDRESS:
				address(req,resp);
				break;
			case OrderServlet.METHOD_FINISH:
				finish(req,resp);
				break;
			default:
				break;
			}
		}
	}
	
	private void address(HttpServletRequest req,HttpServletResponse resp) {
		int userId=((User)req.getSession().getAttribute("s_user")).getId();
		List<ReceiveAddress> addrs;
		try {
			addrs=ServiceDAOFactory.getReceiveAddressService().findByUserId(userId);
//			JSONObject json=new JSONObject();
//			JSONArray array=new JSONArray();
			com.alibaba.fastjson.JSONObject json=new com.alibaba.fastjson.JSONObject();
			com.alibaba.fastjson.JSONArray array=new com.alibaba.fastjson.JSONArray();
			for(ReceiveAddress receiveAddress:addrs) {
				com.alibaba.fastjson.JSONObject json1=(com.alibaba.fastjson.JSONObject)JSON.toJSON(receiveAddress);
				array.add(json1);
//				JSONObject jsonDetail=new JSONObject();
//				jsonDetail.put("id", receiveAddress.getId());
//				jsonDetail.put("userId", receiveAddress.getUserId());
//				jsonDetail.put("fullAddress", receiveAddress.getFullAddress());
//				jsonDetail.put("mobile", receiveAddress.getMobile());
//				jsonDetail.put("phone", receiveAddress.getPhone());
//				jsonDetail.put("pastalCode", receiveAddress.getPostalCode();
//				jsonDetail.put("receiveName", ReceiveAddress.getReceiveName());
//				array.put(jsonDetail);
			}
			json.put("addrs", array);
			PrintWriter out=resp.getWriter();
			out.println(json.toString());
			out.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("static-access")
	private void finish(HttpServletRequest req,HttpServletResponse resp) {
		ReceiveAddress addr=new ReceiveAddress();
		Order order=new Order();
		HttpSession session=req.getSession();
		try {
			String receiveName=req.getParameter("receiveName");
			String fullAddress=req.getParameter("fullAddress");
			String postalCode=req.getParameter("postalCode");
			String phone=req.getParameter("phone");
			String mobile=req.getParameter("mobile");
			String addressId=req.getParameter("addressId");
			
			int userId=((User)session.getAttribute("s_user")).getId();
			Map<Integer, CartItem> map=(Map<Integer, CartItem>)session.getAttribute("s_car");
			if(map.isEmpty()) {
				req.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(req, resp);
			}
			addr.setUserId(userId);
			addr.setFullAddress(fullAddress);
			addr.setReceiveName(receiveName);
			addr.setPostalCode(postalCode);
			addr.setPhone(phone);
			addr.setMobile(mobile);
//			addr.setId(Integer.parseInt(addressId));
			
			order=new Order();
			order.setFullAddress(addr.getFullAddress());
			order.setUserId(userId);
			order.setMobile(addr.getMobile());
			order.setOrderDesc("desc demo");
			order.setOrderTime(System.currentTimeMillis());
			order.setPhone(addr.getPhone());
			order.setPostalCode(addr.getPostalCode());
			order.setReceiveName(addr.getReceiveName());
			order.setStatus(0);
//			order.setTotalPrice(total(map));
			
			ReceiveAddressService service=ServiceDAOFactory.getReceiveAddressService();
			if((service).findById(addr.getId())==null) {
				(service).save(addr);
			}
			
			ServiceDAOFactory.getOrderService().save(order);
			session.setAttribute("s_car", order.getId());
			req.setAttribute("totalDang", total(map));
			map.clear();
//			req.setAttribute("orderId", order.getId());
//			req.setAttribute("totalPrice", order.getTotalPrice());
			req.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(req, resp);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void submit(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("/WEB-INF/view/order/address_form.jsp").forward(req, resp);
	}
	
	@SuppressWarnings("static-access")
	public double total(Map<Integer, CartItem> map) {
		double totalPrice=0.0;
		for(Map.Entry<Integer, CartItem> entry:map.entrySet()) {
			totalPrice+=entry.getValue().getNum()*entry.getValue().getPro().getDangPrice();
		}
		BigDecimal bd=new BigDecimal(totalPrice);
		BigDecimal bd1=bd.setScale(2, bd.ROUND_HALF_UP);
		return bd1.doubleValue();
	}
	
	private void confirm(HttpServletRequest req,HttpServletResponse resp,Map<Integer, CartItem> map) throws ServletException, IOException {
		req.setAttribute("totalDang", total(map));
		req.setAttribute("s_car", map);
		req.getRequestDispatcher("/WEB-INF/view/order/order_info.jsp").forward(req, resp);
	}
}
